package com.android.jr_infraredcamera.utils
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.util.Log
/**
 * @author 战神族灬小火
 * @date 2025/3/4
 * @description
 */


class UsbPermissionHelper(private val context: Context) {

    companion object {
        private const val ACTION_USB_PERMISSION = "com.example.USB_PERMISSION"
        private const val TAG = "===UsbPermissionHelper==="
    }

    private val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager

    // 目标设备（你可以根据实际条件进行筛选）
    var targetDevice: UsbDevice? = null
        private set

    // 广播接收器，用于监听 USB 授权结果
    private val usbReceiver = object : BroadcastReceiver() {
        override fun onReceive(ctx: Context?, intent: Intent?) {
            if (intent == null) return
            if (ACTION_USB_PERMISSION == intent.action) {
                synchronized(this) {
                    val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        device?.let {
                            Log.i(TAG, "USB 设备授权成功: ${it.deviceName}")
                            // 授权成功后，可以继续操作设备，如打开设备、初始化流等

                        }
                    } else {
                        Log.e(TAG, "USB 设备授权被拒绝: ${device?.deviceName}")
                    }
                }
            }
        }
    }

    // 注册广播接收器
    fun registerReceiver() {
        val filter = IntentFilter(ACTION_USB_PERMISSION)
        context.registerReceiver(usbReceiver, filter)
    }

    // 注销广播接收器
    fun unregisterReceiver() {
        context.unregisterReceiver(usbReceiver)
    }

    // 获取 USB 设备列表，并选择目标设备（例如根据 VendorId 或 ProductId 筛选）
    fun findTargetDevice(vendorId: Int, productId: Int): UsbDevice? {
        val deviceList = usbManager.deviceList
        for (device in deviceList.values) {
            Log.i(TAG, "找到设备: ${device.deviceName}, Vendor: ${device.vendorId}, Product: ${device.productId}")
            if (device.vendorId == vendorId && device.productId == productId) {
                targetDevice = device
                break
            }
        }
        return targetDevice
    }

    // 请求 USB 设备授权
    fun requestPermission() {
        targetDevice?.let { device ->
            val permissionIntent = PendingIntent.getBroadcast(
                context,
                0,
                Intent(ACTION_USB_PERMISSION),
                PendingIntent.FLAG_MUTABLE // Android 12 及以上需使用 FLAG_MUTABLE 或 FLAG_IMMUTABLE，根据情况选择
            )
            usbManager.requestPermission(device, permissionIntent)
        } ?: run {
            Log.e(TAG, "未找到目标 USB 设备")
        }
    }
}
